import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, Empty, Form, Icon, Input, message, Row, Select, Typography } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import moment from 'moment';
import useDictionary from '@/hooks/useDictionary';
import { createDictionary } from '@/dictionary';
import { formatDateRange } from '@/utils/utils';
import RangePicker from '@/pages/Recruitment/containers/resume/RangePicker';
import FormContainer from './FormContainer';

const { Text } = Typography;

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

const [workExperienceList, getWorkExperienceText] = createDictionary('WORK_EXPERIENCE_DICT');

/**
 * 员工档案 - 工作经历
 */
const WorkExperienceSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 字典数据
    const [industryTypeList, getIndustryTypeText] = useDictionary('industryType');
    // 列表管理
    const {
        list: workList,
        remove: workListRemove,
        push: workListPush,
        getKey: workListGetKey,
        resetList: workListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        workListReset(formData.workList);
    }, [workListReset, formData.workList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('workList', { initialValue: formData.workList || [] });
    }, [formData.workList]);

    // 保存
    const handleSubmit = async values => {
        const workListObject =
            values.workExperience === 1 &&
            workList.map((item, index) => {
                const key = workListGetKey(index);
                return {
                    startTime:
                        values.startTime[key]?.[0] && values.startTime[key][0].format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    endTime:
                        values.startTime[key]?.[1] && values.startTime[key][1].format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    organize: values.organize[key],
                    industry: values.industry[key],
                    post: values.post[key],
                    reason: values.reason[key],
                    areaCode: values.areaCode[key],
                    approveName: values.approveName[key],
                    approvePhone: values.approvePhone[key]
                };
            });
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            workExperience: values.workExperience,
            newList: workListObject || []
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange({
                workExperience: submitData.workExperience,
                workList: submitData.newList
            });
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        workListReset(formData.workList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (workList.length === 0) {
            workListPush({});
        }
    };

    // 处理日期为空的情况
    const preprocessDateRange = (startDate, endDate) => [startDate && moment(startDate), endDate && moment(endDate)];

    // render
    return (
        <FormContainer
            ref={formRef}
            title="工作经验"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
            {...props}
        >
            {({ getFieldDecorator, getFieldValue }, editStatus) => (
                <div className="dynamicList">
                    <Row gutter={24} style={{ marginBottom: '10px' }}>
                        <Col span={24}>
                            <Form.Item label="工作经验">
                                {editStatus ? (
                                    getFieldDecorator('workExperience', {
                                        initialValue: formData?.workExperience ?? undefined,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择工作经验'
                                            }
                                        ]
                                    })(
                                        <Select
                                            getPopupContainer={trigger => trigger.parentElement}
                                            placeholder="请选择工作经验"
                                        >
                                            {workExperienceList?.map(item => (
                                                <Select.Option value={item.value} key={item.value}>
                                                    {item.text}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    )
                                ) : (
                                    <Text>{getWorkExperienceText(formData?.workExperience) || '--'}</Text>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {(editStatus ? getFieldValue('workExperience') : formData?.workExperience) === 1 && (
                        <>
                            {workList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                            <div className="dynamicListContainer">
                                {workList.map((item, index) => (
                                    <div key={workListGetKey(index)} className="dynamicListItem">
                                        {editStatus && props.isEntryGuide && (
                                            <div className="dynamicListItemHeader">工作经验 {index + 1}</div>
                                        )}
                                        {editStatus && (
                                            <Icon
                                                onClick={() => workListRemove(index)}
                                                className="dynamicListClose"
                                                type="close-circle"
                                                theme="filled"
                                            />
                                        )}

                                        <Form.Item label="起止时间">
                                            {editStatus ? (
                                                getFieldDecorator(`startTime[${workListGetKey(index)}]`, {
                                                    initialValue: item?.startTime
                                                    ? preprocessDateRange(item?.startTime, item?.endTime) : undefined,
                                                    rules: [{ required: true, message: '请选择起止时间' }]
                                                })(<RangePicker />)
                                            ) : (
                                                <Text>
                                                    {formatDateRange(item?.startTime, item?.endTime, 'YYYY-MM-DD') ||
                                                        '--'}
                                                </Text>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="工作单位">
                                            {editStatus ? (
                                                getFieldDecorator(`organize[${workListGetKey(index)}]`, {
                                                    initialValue: item?.organize ?? undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入工作单位'
                                                        },
                                                        {
                                                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                            message: '此处不能输入空格'
                                                        },
                                                        {
                                                            min: 1,
                                                            max: 50,
                                                            message: '请输入1~50个字符'
                                                        }
                                                    ]
                                                })(<Input placeholder="请输入工作单位" />)
                                            ) : (
                                                <div className="multiLineText">{item?.organize || '--'}</div>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="行业/主营业务">
                                            {editStatus ? (
                                                getFieldDecorator(`industry[${workListGetKey(index)}]`, {
                                                    initialValue: item?.industry !== '' ? item?.industry : undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选择行业/主营业务'
                                                        }
                                                    ]
                                                })(
                                                    <Select
                                                        getPopupContainer={trigger => trigger.parentElement}
                                                        placeholder="请选择"
                                                    >
                                                        {industryTypeList?.map(v => (
                                                            <Select.Option value={v?.value} key={v?.value}>
                                                                {v?.text}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                )
                                            ) : (
                                                <Text>{getIndustryTypeText(item?.industry) || '--'}</Text>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="职位职级">
                                            {editStatus ? (
                                                getFieldDecorator(`post[${workListGetKey(index)}]`, {
                                                    initialValue: item?.post ?? undefined,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请输入职位职级'
                                                        },
                                                        {
                                                            min: 1,
                                                            max: 50,
                                                            message: '请输入1~50个字符'
                                                        },
                                                        {
                                                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                            message: '此处不能输入空格'
                                                        }
                                                    ]
                                                })(<Input placeholder="请输入职位职级" />)
                                            ) : (
                                                <div className="multiLineText">{item?.post || '--'}</div>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="离职原因">
                                            {editStatus ? (
                                                getFieldDecorator(`reason[${workListGetKey(index)}]`, {
                                                    initialValue: item?.reason ?? undefined,
                                                    rules: [{ max: 50, message: '字数不能超过50个字符' }]
                                                })(<Input placeholder="请输入" maxLength={50} />)
                                            ) : (
                                                <Text>{item?.reason || '--'}</Text>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="证明联系人">
                                            {editStatus ? (
                                                getFieldDecorator(`approveName[${workListGetKey(index)}]`, {
                                                    initialValue: item?.approveName ?? undefined
                                                })(
                                                    <Input
                                                        minLength={1}
                                                        maxLength={50}
                                                        placeholder="请输入"
                                                    />
                                                )
                                            ) : (
                                                <Text>{item?.approveName || '--'}</Text>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="手机号码">
                                            {editStatus ? (
                                                getFieldDecorator(`approvePhone[${workListGetKey(index)}]`, {
                                                    initialValue: item?.approvePhone ?? undefined,
                                                    rules: [
                                                        {
                                                            validator(rule, value, callback) {
                                                                const regex = /^\d{7,11}$/;
                                                                if (!value) {
                                                                    callback();
                                                                } else if (!regex.test(value)) {
                                                                    callback('只能输入7-11位数字');
                                                                }
                                                                callback();
                                                            }
                                                        }
                                                    ]
                                                })(
                                                    <Input
                                                        maxLength={20}
                                                        placeholder="请输入"
                                                        addonBefore={getFieldDecorator(
                                                            `areaCode[${workListGetKey(index)}]`,
                                                            {
                                                                initialValue:
                                                                    workList[workListGetKey(index)]?.areaCode || '86'
                                                            }
                                                        )(
                                                            <Select
                                                                getPopupContainer={trigger => trigger.parentElement}
                                                                placeholder="区号"
                                                                style={{ width: 80 }}
                                                            >
                                                                <Select.Option value="86">+86</Select.Option>
                                                                <Select.Option value="65">+65</Select.Option>
                                                            </Select>
                                                        )}
                                                    />
                                                )
                                            ) : (
                                                <Text>
                                                    {item.approvePhone
                                                        ? `${item?.areaCode ? `+${item.areaCode}` : ''} ${
                                                              item.approvePhone
                                                          }`
                                                        : '--'}
                                                </Text>
                                            )}
                                        </Form.Item>
                                    </div>
                                ))}
                            </div>
                            {editStatus ? (
                                <Button className="dynamicListAddButton" block onClick={() => workListPush({})}>
                                    +添加工作经历
                                </Button>
                            ) : null}
                        </>
                    )}
                </div>
            )}
        </FormContainer>
    );
};

// prop
WorkExperienceSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

WorkExperienceSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default WorkExperienceSection;
